import TauTable from '@/components/TauTable';
import { toJS } from 'mobx';
import React, { useCallback } from 'react';
import { column, orderModel } from '../stores/definitions';
import { t } from '@lingui/macro';
import { Dialog } from '@alifd/next';
import { useStore } from '@/hooks';
import PopConfirmSwitch from './PopconfirmSwitch';

function TicketTable(props) {
  const {
    rsOrder,
    inForm = false,
    isViewMode = true,
    refundInfo = [],
  } = props;
  const { rsOrderStore: store } = useStore();

  const reqRefundTickets = getRefundingTicket(refundInfo);

  const subModel = orderModel.rsOrder.ticketInfos[0];
  const mapper = useCallback((row, idx) => {
    const matchRefundInfo = reqRefundTickets.find(({ ticketCode }) => (ticketCode === row.ticketCode)) || {};
    const isRefunding = !_.isEmpty(matchRefundInfo);
    return {
      ...row,
      id: `${row.ticketCode}-${idx}`,
      ticketTime: rsOrder?.shiftTime,
      isRefunding,
    };
  });

  // 退款忽略
  const ignoreRefund = async (state, ticketInfo) => {
    const newTicketInfo = rsOrder?.ticketInfo.reduce((res, cur) => {
      const { ticketCode } = cur;
      if (ticketInfo.ticketCode === ticketCode) {
        cur.ignore = state;
      }
      res.push(cur);
      return res;
    }, []);
    const newOrder = _.cloneDeep(rsOrder);
    const param = {};
    _.assign(param, {
      id: newOrder?.orderNo,
      rsOrder: {
        ...newOrder,
        ticketInfo: newTicketInfo,
      },
    });
    try {
      await store.update(param);
    } catch (error) {
      Dialog.error({
        content: t`${error.source.message}`,
      });
    }
  };

  // 获取更多列
  const getMoreColumns = () => {
    if (store.orderStatus === '4' || isViewMode) return [];
    const res = [
      {
        title: t`忽略退款`,
        cell: (_, __, record) => {
          const { ignore: value, isRefunding } = record;
          // 中港通是否退款
          const isOperatorRefund = !!record?.operatorRefundTime;
          return (
            <PopConfirmSwitch
              value={value}
              show={isOperatorRefund && isRefunding}
              onClick={async (v) => await ignoreRefund(v, record)}
            />
          );
        },
      },
    ];
    return res;
  };

  // 获取正在申请退款的车票
  function getRefundingTicket(data) {
    const refundsInfo = _.cloneDeep(data) || [];
    if (refundsInfo.length <= 0) return [];

    const allTicket = refundsInfo?.reduce((res, cur) => {
      const { type, ticketRefundInfos = [] } = cur;
      if (type !== '1') {
        res.push(...ticketRefundInfos);
      }
      return res;
    }, []);
    return allTicket;
  }

  return (
    <div style={{ padding: inForm ? '' : '20px 300px 20px 50px' }}>
      <TauTable
        size={inForm ? 'small' : 'medium'}
        hidePagination
        dataSource={toJS(rsOrder?.ticketInfos?.map(mapper))}
        primaryKey="id"
        columns={[
          column('ticketCode', { width: 188 }, subModel),
          column('ticketPrice', { width: 188 }, subModel),
          column('rsTicketType', { width: 188 }, subModel),
          column('stateName', { width: 188 }, subModel),
          ...getMoreColumns(),
        ]}
      />
    </div>
  );
}
export default TicketTable;
